<?php

namespace app\selladmin\controller;

use app\selladmin\controller\CommonController;
use app\selladmin\model\Store;
use app\selladmin\model\Order;
use app\selladmin\model\Staff;
use app\selladmin\model\Item;
use app\selladmin\model\Custom;
use app\selladmin\model\CtmStaff;
use app\selladmin\model\Gallery;
use app\selladmin\model\Sms;
use app\util\Utils;
use think\Db;
use think\Validate;
use app\selladmin\model\StaffStore;
use app\selladmin\model\ProvCityArea;
use app\selladmin\model\Admin;
use app\selladmin\model\Servicenews;
use app\selladmin\model\Expercard;
use app\selladmin\model\Refund;
use app\selladmin\model\StoreSaveRecord;
use app\selladmin\model\RedpacketCode;
use app\selladmin\model\Selladmin;

class StoreController extends CommonController {
    /*
     * 店铺列表
     * author xfwed 
     * date 2017.08.02
     */

    public function StoreList() {
        //返回销售人员列表
        $id = session("S_ID");
        $row = Selladmin::where('id','=',  $id)->field('level')->find();
        if($row['level'] == Selladmin::LEVEL_0 || $row['level'] == Selladmin::LEVEL_1){
            $selladminlist=Selladmin::where('level','in',[Selladmin::LEVEL_2,Selladmin::LEVEL_3])
                    ->field('id,admin_note')
                    ->select();
        }elseif ($row['level'] == Selladmin::LEVEL_2) {
            $selladminlist=Selladmin::where('pid','=',$id)
                    ->field('id,admin_note')
                    ->select();
        }elseif ($row['level'] == Selladmin::LEVEL_3) {
            $selladminlist=Selladmin::where('id','=',  $id)
                    ->field('id,admin_note')
                    ->select();
        }
        //查询地区
        $ProvCityArea = new ProvCityArea();
        $prov = $ProvCityArea->where('level=1')->field('id,name')->select();

        $store = new Store();
        $store_name = input('get.store_name');
        $phone = input('get.phone');
        $adminid = input('get.adminid');
        $provdata = input('get.provdata');
        $storelevel = input('param.level');
        if ($store_name) {
            $where['store_name'] = ['like', "%$store_name%"];
            $query['store_name'] = $store_name;
        }
        if ($phone) {
            $where['keeper_phone'] = $phone;
            $query['keeper_phone'] = $phone;
        }
        if ($adminid) {
            $query['adminid'] = $adminid;
        }
        if ($provdata) {
            $where['prov'] = $provdata;
            $query['provdata'] = $provdata;
        }
        if ($storelevel) {
            $where['level'] = $storelevel;
            $query['level'] = $storelevel;
        }
        $starttime = input('param.starttime');
        $endtime = input('param.endtime');
        if ($endtime && $starttime) {
            $time = strtotime($starttime);
            $time2 = strtotime($endtime) + 24 * 60 * 60;
            $where['add_time'] = array('between', array($time, $time2));
            $query['starttime'] = $starttime;
            $query['endtime'] = $endtime;
        } elseif (empty($endtime) && $starttime) {
            $time = strtotime($starttime);
            $time2 = $time + 24 * 60 * 60;
            $where['add_time'] = array('between', array($time, $time2));
            $query['starttime'] = $starttime;
        }
        $where['auditstore'] = 1;
        $query['auditstore'] = 1;
        $where['is_del'] = 1;
        $query['is_del'] = 1;
        $ctm_id = session('S_ID');
        $selladmin = Selladmin::where('id','=',$ctm_id)->field('id,level')->find();
        $level = $selladmin['level'];
        if($level==0 or $level==1){//超级管理员和总经理
            if ($adminid) {
                $selladminrow = Selladmin::where('id','=',$adminid)->field('id,level')->find();
                if($selladminrow['level'] == 2){
                    $ids = Selladmin::where('pid','=',$adminid)->column('id'); 
                    $where['sell_id']=['in',$ids];  
                }elseif ($selladminrow['level'] == 3) {
                    $where['sell_id']=$adminid;  
                }
              $query['adminid'] = $adminid;
            }  else {
                $where['sell_id']=['<>',0];  
            }
        }elseif ($level==2) {//经理
            if ($adminid) {
                $where['sell_id']=$adminid;  
            }  else {
                $ids = Selladmin::where('pid','=',$ctm_id)->column('id'); 
                $where['sell_id']=['in',$ids];  
            }
        }elseif ($level==3) {//员工
            $where['sell_id']=$ctm_id;  
        }
        $storeList = Store::with('ProvCityArea,Selladmin')
                ->where($where)
                ->field("id,store_name,store_keeper,store_address,keeper_phone,add_time,prov,msg,sell_id,assign,level,expire_time")
                ->order("add_time desc")
                ->paginate(12)
                ->appends($query);
        return view('storelist', [
            'storeList' => $storeList,
            'store_name' => $store_name,
            'phone' => $phone,
            'selladmin' => $selladminlist,
            'adminid' => $adminid,
            'prov' => $prov,
            'provdata' => $provdata,
            'starttime' => $starttime,
            'endtime' => $endtime,
            'level' => $storelevel,
        ]);
    }

    /*
     * 删除店铺
     * author xfwed 
     * date 2017.08.03
     */

    public function DelStore() {
        $session = session(config('adminconfig.USER_AUTH_KEY'));
        if ($session == 24) {
            $this->error('您没有权限操作', url('Store/storelist'));
        }
        $storeObj = new Store();
        $storeWhere['id'] = input('get.id');
        //查询店铺是否有未完成的订单
        $orderObj = new Order();
        $orderwhere['status'] = ['in', '2,3,4'];
        $orderwhere['store_id'] = input('get.id');
        $orddata = $orderObj->where($orderwhere)->select();
        if (!empty($orddata)) {
            return $this->ajaxReturn(0, '还有未完成的订单', null);
        }
        $storesave['is_del'] = 2;
        $delStore = $storeObj->where($storeWhere)->update($storesave);
        //删除员工店铺关联表
        $staffstore = new StaffStore();
        $staffstore->where('store_id', '=', input('get.id'))->delete();
        //用户表is_setshop置0
        $customdata = Custom::where('is_setshop=' . input('get.id'))->find();
        if ($customdata) {
            Custom::where('is_setshop=' . input('get.id'))->update(['is_setshop' => 0]);
        }
        $Where['store_id'] = input('get.id'); //店铺id
        //删除店铺里面的员工信息
        $staffObj = new Staff();
        $staffsave['staff_on'] = 2;
        $staffObj->where($Where)->update($staffsave); //删除员工信息；
        //删除店铺项目信息
        $itemsObj = new Item();
        $itemsave['is_del'] = 1;
        $itemsObj->where($Where)->update($itemsave); //删除项目信息；
        //删除客户注册信息
        $customObj = new Custom();
        $customsave['status'] = 1;
        $customObj->where($Where)->update($customsave); //删除客户注册信息
        if ($delStore) {
            return $this->ajaxReturn(1, '删除成功', null);
        } else {
            return $this->ajaxReturn(0, '删除失败', null);
        }
    }

    /*
     * 查看信息
     * author xfwed
     * date 2017.08.03
     */

    public function ShowMessage() {
        $id = input('param.id');
        //查询店铺信息
        $store = new Store();
        $storeList = $store->StoreInfo($id);
        //查询项目信息
        $item = new Item();
        $item_name = input('get.item_name');
        $itemList = $item->ItemInfo($id, $item_name, 13);
        return view('showmessage', [
            'storeList' => $storeList,
            'item_name' => $item_name,
            'itemList' => $itemList,
            'id' => $id,
        ]);
    }

    /*
     * 查看相册信息
     * author xfwed 
     * date 2017.08.04
     */

    public function ShowImgMessage() {
        $id = input('param.id');
        //查询店铺信息
        $store = new Store();
        $storeList = $store->StoreInfo($id);
        //查询相册信息
        $gallery = new Gallery();
        $galleryList = $gallery->GalleryInfo($id);
        return view('showimgmessage', [
            'storeList' => $storeList,
            'galleryList' => $galleryList,
            'id' => $id,
        ]);
    }

    /*
     * 查看订单信息
     * author xfwed 
     * date 2017.08.04
     */

    public function ShowOrderMessage() {
        $id = input('param.id');
        //查询店铺信息
        $store = new Store();
        $storeList = $store->StoreInfo($id);
        //查询订单信息
        $order = new Order();
        $ord_num = input('get.ord_num');
        $orderList = $order->OrderInfo($id, $ord_num, '', 10);
        return view('showordermessage', [
            'storeList' => $storeList,
            'orderList' => $orderList,
            'ord_num' => $ord_num,
            'id' => $id,
        ]);
    }

    /*
     * 查看员工信息
     * author xfwed 
     * date 2017.08.04
     */

    public function ShowStaffMessage() {
        $id = input('param.id');
        //查询店铺信息
        $store = new Store();
        $storeList = $store->StoreInfo($id);
        //查询员工信息
        $staff = new Staff();
        $telephone = input('get.telephone');
        $staffList = $staff->StaffInfo($id, $telephone, 13);

        return view('showstaffmessage', [
            'storeList' => $storeList,
            'staffList' => $staffList,
            'telephone' => $telephone,
            'id' => $id,
        ]);
    }

    /*
     * 查看客户信息
     * author xfwed 
     * date 2017.08.04
     */

    public function ShowCustomMessage() {
        $id = input('param.id');
        //查询店铺信息
        $store = new Store();
        $storeList = $store->StoreInfo($id);
        //查询员工信息
        $custom = new Custom();
        $custom_name = input('get.custom_name');
        $custom_phone = input('get.custom_phone');
        $customList = $custom->CustomInfo('', $id, $custom_name, $custom_phone, 13);
        return view('showcustommessage', [
            'storeList' => $storeList,
            'customList' => $customList,
            'custom_name' => $custom_name,
            'custom_phone' => $custom_phone,
            'id' => $id,
        ]);
    }

    /*
     * 查看预约信息
     * author xfwed 
     * date 2017.08.04
     */

    public function ShowOnlineMessage() {
        $id = input('param.id');
        //查询店铺信息
        $store = new Store();
        $storeList = $store->StoreInfo($id);
        //查询员工信息
        $ctmstaff = new CtmStaff();
        $onlineList = $ctmstaff->OnlineInfo('', $id, '', 13);
        return view('showonlinemessage', [
            'storeList' => $storeList,
            'onlineList' => $onlineList,
            'id' => $id,
        ]);
    }

    /*
     * 待审核店铺列表
     * author xfwed 
     * date 2019.01.18
     */

    public function AuditStore() {
        $s_id = session('S_ID');
        $row = Selladmin::where('id','=',$s_id)->field('id,level')->find();
        if($row['level'] == 2){
            $adminlist = Selladmin::where('pid','=',$s_id)->field('id,admin_note')->select();
        }  else {
            $adminlist = [];
        }

        $store = new Store();
        $store_name = input('get.store_name');
        $phone = input('get.phone');
        $auditstore = input('get.auditstore');
        $auditstore = isset($auditstore) ? $auditstore : -1;
        $admin = input('get.adminid');
        if ($store_name) {
            $where['store_name'] = ['like', "%$store_name%"];
            $query['store_name'] = $store_name;
        }
        if ($phone) {
            $where['keeper_phone'] = $phone;
            $query['keeper_phone'] = $phone;
        }
        if ($auditstore != -1) {
            $where['auditstore'] = $auditstore;
            $query['auditstore'] = $auditstore;
        } else {
            $where['auditstore'] = ['in', '0,2'];
            //$query['auditstore'] = ['in', '0,2'];
        }
        if ($admin) {
            $query['adminid'] = $admin;
        }
        if($row['level'] == 2){
            if($admin){
               $where['sell_id'] = $admin; 
            }  else {
                $ids = Selladmin::where('pid','=',$s_id)->column('id'); 
                $where['sell_id']=['in',$ids];  
            }
        }  else {
            $where['sell_id']=-1;  //其他级别没有审核权限
        }
        
        $where['is_del'] = 1;
        $query['is_del'] = 1;
        $storeList = Store::with('ProvCityArea,Selladmin')
                ->where($where)
                ->field("id,store_name,store_keeper,store_address,keeper_phone,add_time,prov,auditstore")
                ->order("add_time desc")
                ->paginate(12)
                ->appends($query);
        return view('auditstore', [
            'storeList' => $storeList,
            'store_name' => $store_name,
            'phone' => $phone,
            'adminlist' => $adminlist,
            'admin' => $admin,
        ]);
    }

    /*
     * 待审核店铺详情
     * author xfwed 
     * date 2017.08.07
     */

    public function AuditStoreDetails() {
        $id = input('param.id');
        //查询店铺信息
        $store = new Store();
        $storeList = $store->StoreInfo($id);
        //查询短信历史
        $smslist = Sms::where('phone=' . $storeList['keeper_phone'] . ' and type=' . Sms::TYPE_4)->select();
        return view('auditstoredetails', [
            'storeList' => $storeList,
            'smslist' => $smslist,
        ]);
    }

    /*
     * 审核店铺发送短信
     * 作者 xfwed
     * 日期 2017-08-07
     */

    public function sendSms() {
        $rule = [
            'phone' => 'require|length:11',
            'content' => 'require',
        ];
        $msg = [
            'phone.require' => '手机号必须',
            'phone.length' => '手机号长度为11',
            'content.require' => '短信必填',
        ];
        $all = input('post.');
        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();
            return $this->ajaxReturn(1, $error, null);
        }
        $telephone = $all['phone'];
        $staffRow = Staff::where('telephone', '=', $telephone)
                ->where('staff_on', '=', Staff::STAFF_ON_1)
                ->find();
        if (is_null($staffRow)) {
            return $this->ajaxReturn(10004, '手机号未注册', null);
        }

        $content = $all['content'];
        $sendResult = Utils::sendSms($telephone, $content);
        if ($sendResult['code'] == 'success') {
            //写入短信内容
            $codeData = [
                'type' => Sms::TYPE_4,
                'phone' => $telephone,
                'content' => $content,
                'add_time' => time(),
            ];
            Sms::insert($codeData);
            return $this->ajaxReturn(0, '短信发送成功', null);
        } else {
            return $this->ajaxReturn(10005, $sendResult['msg'], null);
        }
    }

    /*
     * 审核店铺
     * 作者 xfwed
     * 日期 2017-08-07
     */

    public function Audit() {
        $all = input('post.');
        if ($all['auditstore'] == 2 and empty($all['why'])) {
            return $this->ajaxReturn(0, "请填写失败原因", null);
        }
        $Data = [
            'auditstore' => $all['auditstore'],
            'why' => $all['why'],
        ];
        $aa = Store::where('id', '=', $all['store_id'])->update($Data);
        if ($aa) {
            $store_id = $all['store_id'];
            $auditstore = $all['auditstore'];

            $storeRow = StaffStore::with('store,staff')->where('store_id', '=', $store_id)->find();

            if ($auditstore == 1) {
                //审核通过

                $staff_id = $storeRow['staff']['id'];
                $count = StaffStore::where('staff_id', '=', $staff_id)->count();
                if ($count > 1) {
                    $content = "恭喜！您提交的 [{$storeRow['store']['store_name']}] 入驻申请通过审核，您可以在 我的>设置>账号管理 中切换店铺账号去完善内容喲";
                } else {
                    $content = "恭喜！您提交的 [{$storeRow['store']['store_name']}] 入驻申请通过审核，快点下载商户版去完善内容开始接单吧";
                }
            } else if ($auditstore == 2) {
                //审核不通过

                $why = $all['why'];
                $content = "抱歉！您提交的 [{$storeRow['store']['store_name']}] 入驻申请未通过审核，原因：[{$why}]，客服热线：400-801-3680";
            }

            //给店铺发推送
            $msgContent = Utils::getColoredString($content);
            $pushContent = Utils::getPushString($content);
            $userid = $storeRow['staff']['id'];
            $alias = $storeRow['staff']['telephone'] . $store_id;
            Utils::sendServicenews(Servicenews::TITLEID_13, 0, 0, $msgContent, $userid, Servicenews::TYPE_1, $store_id, [
                'title' => '店铺审核消息',
                'content' => $pushContent,
                'alias_type' => Servicenews::ALIAS_TYPE_1,
                'alias' => $alias,
            ]);
            return $this->ajaxReturn(1, "审核成功", null);
        } else {
            return $this->ajaxReturn(0, "审核失败", null);
        }
    }

    /*
     * 修改店铺信息
     * 作者 xfwed
     * 日期 2017-10-18
     */

    public function editStore() {
        $session = session(config('adminconfig.USER_AUTH_KEY'));
        if ($session == 24) {
            $this->error('您没有权限操作', url('Store/storelist'));
        }
        $id = input('param.id');
        //查询店铺信息
        $store = new Store();
        $storedata = $store->StoreInfo($id);
        if (!$_POST) {
            //查询地区
            $ProvCityArea = new ProvCityArea();
            $prov = $ProvCityArea->where('level=1')->field('id,name')->select();
            return view('editstore', ['storedata' => $storedata, 'prov' => $prov]);
        } else {
            $rule = [
                'store_name' => 'require',
                'store_phone' => 'require',
                'store_address' => 'require',
                'prov' => 'require',
                'city' => 'require',
                'area' => 'require',
                'longitude' => 'require',
                'latitude' => 'require',
                'adminname' => 'require',
            ];
            $msg = [
                'store_name.require' => '店铺名称必须',
                'store_phone.require' => '店铺电话必须',
                'store_address.require' => '详细地址必须',
                'prov.require' => '省份必须',
                'city.require' => '城市必须',
                'area.require' => '区县必须',
                'longitude.require' => '经度必须',
                'latitude.require' => '纬度必须',
                'adminname.require' => '请输入你的密码',
            ];
            $all = input('post.');
            $validate = new Validate($rule, $msg);

            if (!$validate->check($all)) {
                $error = $validate->getError();
                $this->error($error);
            }
            //验证添加者身份
            $addid = session('A_ID');
            $adminfind = Admin::where('id=' . $addid)->find();
            if ($adminfind['admin_pwd'] != md5($all['adminname'])) {
                $this->error('你的密码错误，修改失败');
            }
            $data['store_name'] = $all['store_name'];
            $data['store_phone'] = $all['store_phone'];
            $data['prov'] = $all['prov'];
            $data['city'] = $all['city'];
            $data['area'] = $all['area'];
            $data['store_address'] = $all['store_address'];
            $data['longitude'] = $all['longitude'];
            $data['latitude'] = $all['latitude'];
            $save = Store::where("id=" . $all['id'])->update($data);
            //写入修改记录
            $storesaverecord = new StoreSaveRecord();
            $store_id = $all['id'];
            $old = $storedata['store_name'] . '^' . $storedata['store_phone'] . '^' . $storedata['prov'] . '^' . $storedata['city'] . '^' . $storedata['area'] . '^' . $storedata['store_address'] . '^' . $storedata['longitude'] . '^' . $storedata['latitude'];
            $new = $data['store_name'] . '^' . $data['store_phone'] . '^' . $data['prov'] . '^' . $data['city'] . '^' . $data['area'] . '^' . $data['store_address'] . '^' . $data['longitude'] . '^' . $data['latitude'];
            $record = $storesaverecord->insertRecord($store_id, $old, $new);
            if ($save) {
                $this->success('修改成功');
            } else {
                $this->success('修改失败');
            }
        }
    }

    /*
     * 查询城市
     * author xfwed
     * date 2017.10.18
     */

    public function selectcity() {
        $id = input('param.id');
        $ProvCityArea = new ProvCityArea();
        $city = $ProvCityArea->where('pid=' . $id)->field('id,name')->select();
        return Utils::ajaxReturn(0, '查询成功', $city);
    }

    /*
     * 查询区县
     * author xfwed
     * date 2017.10.18
     */

    public function selectarea() {
        $id = input('param.id');
        $ProvCityArea = new ProvCityArea();
        $area = $ProvCityArea->where('pid=' . $id)->field('id,name')->select();
        return Utils::ajaxReturn(0, '查询成功', $area);
    }

    /*
     * 下架体验卡
     * author xfwed 
     * date 2017.11.03
     */

    public function EndExpercard() {
        $session = session(config('adminconfig.USER_AUTH_KEY'));
        if ($session == 24) {
            $this->error('您没有权限操作', url('Store/storelist'));
        }
        $ExpercardObj = new Expercard();
        $store_id = input('get.id');
        //查询店铺是否有未结束的体验卡
        $experdata = $ExpercardObj->where("store_id", '=', $store_id)->where('end_time', '>=', time())->select();
        if (empty($experdata)) {
            return $this->ajaxReturn(0, '该店铺没有有效的体验卡', null);
        } else {
            $savedata = $ExpercardObj->where("store_id", '=', $store_id)->where('end_time', '>=', time())->update(['end_time' => time()]);

            if ($savedata) {
                return $this->ajaxReturn(1, '下架成功', null);
            } else {
                return $this->ajaxReturn(0, '下架失败', null);
            }
        }
    }

    /*
     * 店铺黑名单
     * author xfwed 
     * date 2017.11.24
     */

    public function BlackStore() {
        $session = session(config('adminconfig.USER_AUTH_KEY'));
        if ($session == 24) {
            $this->error('您没有权限操作', url('Store/storelist'));
        }
        $refund = new Refund();
        $phone = input('get.phone');
        $salesman = input('get.salesman');
        $addauthor = input('get.addauthor');
        if ($phone) {
            $where['phone'] = $phone;
            $query['phone'] = $phone;
        }
        if ($salesman) {
            $where['salesman'] = $salesman;
            $query['salesman'] = $salesman;
        }
        if ($addauthor) {
            $where['addauthor'] = $addauthor;
            $query['addauthor'] = $addauthor;
        }
        $where = isset($where) ? $where : [];
        $query = isset($query) ? $query : [];

        $storeList = Refund::where($where)
                ->order("addtime desc")
                ->paginate(12)
                ->appends($query);
        return view('blackstore', [
            'storeList' => $storeList,
            'phone' => $phone,
            'salesman' => $salesman,
            'addauthor' => $addauthor,
        ]);
    }

    /*
     * 添加黑名单
     * author xfwed 
     * date 2017.11.24
     */

    public function addBlackStore() {
        if (!$_POST) {
            return view('addblackstore', '');
        } else {
            $data['name'] = input('param.name');
            $data['phone'] = input('param.phone');
            $data['cardnumber'] = input('param.cardnumber');
            $data['storename'] = input('param.storename');
            $data['buslic'] = input('param.buslic');
            $data['storeaddress'] = input('param.storeaddress');
            $data['salesman'] = input('param.salesman');
            $data['addauthor'] = input('param.addauthor');
            $data['addtime'] = time();
            $add = Refund::insert($data);
        }

        if ($add) {
            $this->success('添加成功', '');
        } else {
            $this->error('添加成功', '');
        }
    }

    /*
     * 图表展示
     * author xfwed
     * date 2018-01-12
     * */

    public function StoreEcharts() {
        $yeardata = input('param.year');
        $year = isset($yeardata) ? $yeardata : date('Y');
        //月份
        for ($m = 1; $m <= 12; $m++) {
            $month[] = $m . "月";
        }

        $prov = input('param.prov');
        $city = input('param.city');
        $area = input('param.area');
        if ($area) {
            $where['area'] = $area;
        } else {
            if ($city) {
                $where['city'] = $city;
            } else {
                if ($prov) {
                    $where['prov'] = $prov;
                }
            }
        }
        $where['is_del'] = 1;

        //用户量（总）
        $StoreData = Store::where("FROM_UNIXTIME(add_time,'%Y') = '" . $year . "'")
                ->where($where)
                ->field("FROM_UNIXTIME(add_time, '%m') AS m,count(id) AS c")
                ->group('m')
                ->order('m asc')
                ->select();
        $storeReturn_data = array(
            '01' => 0, '02' => 0, '03' => 0, '04' => 0, '05' => 0, '06' => 0, '07' => 0, '08' => 0, '09' => 0, '10' => 0, '11' => 0, '12' => 0,
        );
        foreach ($StoreData as $value) {
            $storeReturn_data[$value['m']] = $value['c'];
        }

        $currentYear = date('Y');
        $years = $currentYear + 1;

        //查询地区
        $ProvCityArea = new ProvCityArea();
        $provdata = $ProvCityArea->where('level=1')->field('id,name')->select();

        return view('storeecharts', [
            'month' => implode(',', $month),
            'storeData' => implode(',', array_values($storeReturn_data)), //用户量总
            'years' => $years,
            'year' => $year,
            'currentYear' => $currentYear,
            'prov' => $prov,
            'city' => $city,
            'area' => $area,
            'provdata' => $provdata
        ]);
    }

    /* 按照省份导出店铺信息
     * author xfwed
     * date 2018-01-17
     */

    public function storeExcel() {
        $prov = input('param.prov');
        $starttime = input('param.starttime');
        $endtime = input('param.endtime');
        if (!empty($endtime) && !empty($starttime)) {
            $time = $starttime;
            $time2 = $endtime + 24 * 60 * 60;
            $where['add_time'] = array('between', array($time, $time2));
        } elseif (empty($endtime) && !empty ($starttime)) {
            $time = $starttime;
            $time2 = $time + 24 * 60 * 60;
            $where['add_time'] = array('between', array($time, $time2));
        }
        
        if ($prov) {
            $where['prov']=$prov;
            $provData = ProvCityArea::where('id', '=', $prov)->find();
            $provname = $provData['name'];
        }  else {
            $provname = '时间段';
        }
        $where['is_del'] = 1;
        $where['auditstore'] = 1;
        $expTitle = '克克美店铺';
        $expTableData = Store::where($where)->field('store_name,store_address,store_keeper,keeper_phone,auditstore,add_time')->order('add_time desc')->select();
        
        $xlsTitle = iconv('utf-8', 'gb2312', $expTitle . '(' . $provname . '-共计' . count($expTableData) . '条)'); //文件名称
        $fileName = $xlsTitle; //or $xlsTitle 文件名称可根据自己情况设定
        if (empty($expTableData)) {
            $this->error('本地区没有入驻的店铺，请选择其他地区试试');
        }
        $ii = 3;
        Vendor('PHPExcel.PHPExcel');
        $objPHPExcel = new \PHPExcel();
        $cellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ');
        $objPHPExcel->getActiveSheet(0)->mergeCells('A1:' . $cellName[6 - 1] . '1'); //合并单元格
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', $expTitle . '(' . $provname . ')' . '  Export time:' . date('Y-m-d H:i:s'));
        $objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setSize(18);
        $objPHPExcel->getActiveSheet()->getStyle('A1')->applyFromArray(//居中加粗
                array(
                    'font' => array(
                        'bold' => true
                    ),
                    'alignment' => array(
                        'horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_CENTER
                    )
                )
        );
        $objPHPExcel->getActiveSheet()->getRowDimension('1')->setRowHeight(30); // 第一行的默认高度
        $objPHPExcel->getActiveSheet()->getRowDimension('2')->setRowHeight(25); // 第一行的默认高度
        $objPHPExcel->getActiveSheet()->getDefaultRowDimension()->setRowHeight(20); // 所有单元格默认高度
        $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setAutoSize(true); //设置宽width
        $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setAutoSize(true); //设置宽width
        $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setAutoSize(true); //设置宽width
        $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setAutoSize(true); //设置宽width
        $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setAutoSize(true); //设置宽width
        $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setAutoSize(true); //设置宽width
        $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(20); //设置宽width
        $objPHPExcel->getActiveSheet()->getStyle('A1')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER); //垂直居中
        $objPHPExcel->getActiveSheet()->getStyle('2')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER); //垂直居中
        $styleArray = array(
            'borders' => array(
                'allborders' => array(
                    //'style' => PHPExcel_Style_Border::BORDER_THICK,//边框是粗的  
                    'style' => \PHPExcel_Style_Border::BORDER_THIN, //细边框  
                //'color' => array('argb' => 'FFFF0000'),  
                ),
            ),
        );
        $objPHPExcel->getActiveSheet()->getStyle('A1:F' . (count($expTableData) + 2))->applyFromArray($styleArray); //这里就是画出从单元格A5到N5的边框，看单元格最右边在哪哪个格就把这个N改为那个字母替代  


        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A2', "店铺名称");
        $objPHPExcel->getActiveSheet()->getStyle('A2')->applyFromArray(array('font' => array('bold' => true)));
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('B2', "负责人");
        $objPHPExcel->getActiveSheet()->getStyle('B2')->applyFromArray(array('font' => array('bold' => true)));
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('C2', "负责人电话");
        $objPHPExcel->getActiveSheet()->getStyle('C2')->applyFromArray(array('font' => array('bold' => true)));
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('D2', "店铺地址");
        $objPHPExcel->getActiveSheet()->getStyle('D2')->applyFromArray(array('font' => array('bold' => true)));
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('E2', "状态");
        $objPHPExcel->getActiveSheet()->getStyle('E2')->applyFromArray(array('font' => array('bold' => true)));
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('F2', "注册时间");
        $objPHPExcel->getActiveSheet()->getStyle('F2')->applyFromArray(array('font' => array('bold' => true)));

        foreach ($expTableData as $key => $val) {
            $tt = 'A' . $ii;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($tt, " " . $val['store_name']); //加  “ ”防止用科学计数法，中间必须有空格，否则无效
            $tt = 'B' . $ii;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($tt, " " . $val['store_keeper']);
            $tt = 'C' . $ii;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($tt, $val['keeper_phone']);
            $tt = 'D' . $ii;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($tt, $val['store_address']);
            $tt = 'E' . $ii;
            if ($val['auditstore'] == 0) {
                $auditstore = '未审核';
            } elseif ($val['auditstore'] == 1) {
                $auditstore = '审核通过';
            } elseif ($val['auditstore'] == 2) {
                $auditstore = '审核失败';
            }
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($tt, $auditstore);
            $tt = 'F' . $ii;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($tt, date('Y-m-d H:i:s', $val['add_time']));
            $ii++;
        }
        ob_end_clean();
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Type: application/vnd.ms-excel;charset=utf-8');
        header('Content-Disposition: attachment;filename="' . $fileName . '.xls"');  //日期为文件名后缀
        header('Cache-Control: max-age=0');
        header("Content-type:application/octet-stream");
        header("Accept-Ranges:bytes");
        header("Pragma: no-cache");
        header("Expires: 0");
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        exit;
    }

    /*
     * 修改客服联系备注
     * author xfwed
     * date 2018-05-30     
     */

    public function SaveMsg() {
        $id = input('param.id');
        $storerow = Store::where('id','=',$id)->field('msg')->find();
        $msg = input('param.msg');
        $msg = $storerow['msg'].'【' . session('S_NAME') . '】' . $msg;
        $result = Store::where('id', '=', $id)->update(['msg' => $msg]);
    }

    /*
     * 项目购买记录
     * author xfwed
     * date 2018-07-03    
     */

    public function BuyRecord() {
        //查询店铺信息
        $store = new Store();
        $store_id=  input('param.store_id');
        $storeList = $store->StoreInfo($store_id);

        $id = input('param.id'); //项目id
        $custom_phone=  input('param.custom_phone');//用户手机号
        if($custom_phone){
            $where['c.custom_phone']=$custom_phone;
            $query['custom_phone'] = $custom_phone;
        }
        
        $where['o.type'] = 2;
        $where['o.status'] = array('>', 1);
        $where['op.pro_id'] = $id;
        $query['type'] = 2;
        $query['status'] = array('>', 1);
        $query['pro_id'] = $id;
        $orderList = Db::table('da_order')
                ->alias('o')
                ->join('custom c', 'o.ctm_id = c.id')
                ->join('ord_pro op', 'o.id = op.ord_id')
                ->where($where)
                ->order('add_time desc')
                ->field("o.id,o.source,o.ord_num,o.ctm_id,o.ordtype,o.pay_money,o.status,o.add_time,o.pay_time,o.store_id,c.custom_name,c.real_name,c.custom_phone,op.number")
                ->paginate(12)
                ->appends($query);
        return view('buyrecord', [
            'orderList' => $orderList,
            'storeList' => $storeList,
            'id'=>$store_id,
            'item_id'=>$id,
            'custom_phone'=>$custom_phone
        ]);
    }

    /*
     * 查看店铺拓客红包
     * author xfwed 
     * date 2018.12.21
     */

    public function redpacket() {
        $id = input('param.id');
        $status = input('param.status');
        $number = input('param.number');

        if (!empty($status)) {
            $where['status'] = $status;
            $query['status'] = $status;
        }
        if (!empty($number)) {
            $where['id'] = ['>=',$number];
            $query['number'] = $number;
        }
        $where['store_id']=$id;
        $query['store_id']=$id;
        
        $redlist=RedpacketCode::where($where)->paginate(12)->appends($query);
        for($i=0;$i<count($redlist);$i++){
            $ctmdata=Custom::where('id','=',$redlist[$i]['ctm_id'])->field('custom_phone')->find();
            $redlist[$i]['custom_phone']=$ctmdata['custom_phone'];
        }
        
        return view('redpacket', [
            'redlist' => $redlist,
            'status' => $status,
            'number' => $number,
            'id' => $id,
        ]);
    }
    
    /* 导出拓客红包
     * author xfwed
     * date 2018-12-21
     */

    public function redpacketExcel() {
        $status = input('param.status');
        $number = input('param.number');
        $id = input('param.id');
        
        if (!empty($status)) {
            $where['status'] = $status;
        }
        if (!empty($number)) {
            $where['id'] = ['>=',$number];
        }
        $where['store_id']=$id;
        $where['status']=2;
        
        $expTableData=RedpacketCode::where($where)->select();
       
        $expTitle = '克克美红包兑换码';
        $xlsTitle = iconv('utf-8', 'gb2312', $expTitle . '(共计' . count($expTableData) . '条)'); //文件名称
        $fileName = $xlsTitle; //or $xlsTitle 文件名称可根据自己情况设定
        $ii = 3;
        Vendor('PHPExcel.PHPExcel');
        $objPHPExcel = new \PHPExcel();
        $cellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ');
        $objPHPExcel->getActiveSheet(0)->mergeCells('A1:' . $cellName[5 - 1] . '1'); //合并单元格
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', $expTitle . '  Export time:' . date('Y-m-d H:i:s'));
        $objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setSize(18);
        $objPHPExcel->getActiveSheet()->getStyle('A1')->applyFromArray(//居中加粗
                array(
                    'font' => array(
                        'bold' => true
                    ),
                    'alignment' => array(
                        'horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_CENTER
                    )
                )
        );
        $objPHPExcel->getActiveSheet()->getRowDimension('1')->setRowHeight(30); // 第一行的默认高度
        $objPHPExcel->getActiveSheet()->getRowDimension('2')->setRowHeight(25); // 第一行的默认高度
        $objPHPExcel->getActiveSheet()->getDefaultRowDimension()->setRowHeight(20); // 所有单元格默认高度
        $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setAutoSize(true); //设置宽width
        $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setAutoSize(true); //设置宽width
        $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setAutoSize(true); //设置宽width
        $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setAutoSize(true); //设置宽width
        $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setAutoSize(true); //设置宽width
        $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setAutoSize(true); //设置宽width
        $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(20); //设置宽width
        $objPHPExcel->getActiveSheet()->getStyle('A1')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER); //垂直居中
        $objPHPExcel->getActiveSheet()->getStyle('2')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER); //垂直居中
        $styleArray = array(
            'borders' => array(
                'allborders' => array(
                    //'style' => PHPExcel_Style_Border::BORDER_THICK,//边框是粗的  
                    'style' => \PHPExcel_Style_Border::BORDER_THIN, //细边框  
                //'color' => array('argb' => 'FFFF0000'),  
                ),
            ),
        );
        $objPHPExcel->getActiveSheet()->getStyle('A1:E' . (count($expTableData) + 2))->applyFromArray($styleArray); //这里就是画出从单元格A5到N5的边框，看单元格最右边在哪哪个格就把这个N改为那个字母替代  


        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A2', "编号");
        $objPHPExcel->getActiveSheet()->getStyle('A2')->applyFromArray(array('font' => array('bold' => true)));
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('B2', "兑换码");
        $objPHPExcel->getActiveSheet()->getStyle('B2')->applyFromArray(array('font' => array('bold' => true)));
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('C2', "金额");
        $objPHPExcel->getActiveSheet()->getStyle('C2')->applyFromArray(array('font' => array('bold' => true)));
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('D2', "状态");
        $objPHPExcel->getActiveSheet()->getStyle('D2')->applyFromArray(array('font' => array('bold' => true)));
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('E2', "注册时间");
        $objPHPExcel->getActiveSheet()->getStyle('E2')->applyFromArray(array('font' => array('bold' => true)));

        foreach ($expTableData as $key => $val) {
            $tt = 'A' . $ii;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($tt, " " . $val['id']); //加  “ ”防止用科学计数法，中间必须有空格，否则无效
            $tt = 'B' . $ii;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($tt, " " . $val['redeem_code']);
            $tt = 'C' . $ii;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($tt, " " . $val['money']);
            $tt = 'D' . $ii;
            if($val['status'] ==1){
                $status = '已兑换';
            }  else {
                $status = '未兑换';
            }
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($tt, $status);
            $tt = 'E' . $ii;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($tt, date('Y-m-d H:i:s', $val['add_time']));
            $ii++;
        }
        ob_end_clean();
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Type: application/vnd.ms-excel;charset=utf-8');
        header('Content-Disposition: attachment;filename="' . $fileName . '.xls"');  //日期为文件名后缀
        header('Cache-Control: max-age=0');
        header("Content-type:application/octet-stream");
        header("Accept-Ranges:bytes");
        header("Pragma: no-cache");
        header("Expires: 0");
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        exit;
    }
    
    /*
     * 添加拓客红包
     * author xfwed
     * date 2018.12.21
     */

    public function addredpacket() {
        if (!$_POST) {
            $id=input('param.id');
            return view('addredpacket', ['id'=>$id]);
        } else {
            $rule = [
                'id' => 'require',
                'number' => 'require',
                'money' => 'require',
            ];
            $msg = [
                'id.require' => '店铺必须',
                'number.require' => '数量必须',
                'money.require' => '金额必须',
            ];
            $all = input('param.');
            $validate = new Validate($rule, $msg);

            if (!$validate->check($all)) {
                $error = $validate->getError();
                $this->error($error);
            }
            $id=input('param.id');
            $number=input('param.number');
            $money=input('param.money');
            
            for($i=0;$i<$number;$i++){
                $redeem_code=RedpacketCode::generateredeemcode($id);
                $data['redeem_code']=$redeem_code;
                $data['money']=$money;
                $data['store_id']=$id;
                $data['add_time']=time();
                $add=RedpacketCode::insert($data);
            }

            if ($add) {
                $this->success('添加成功');
            } else {
                $this->error('添加失败');
            }
        }
    }
    
    /*
     * 分配店铺列表
     * author xfwed 
     * date 2019.01.18
     */

    public function AssignStore() {
        //返回销售人员列表
        $id = session("S_ID");
        $row = Selladmin::where('id','=',  $id)->field('level')->find();
        if($row['level'] == Selladmin::LEVEL_0 || $row['level'] == Selladmin::LEVEL_1){
            $selladminlist=Selladmin::where('level','in',Selladmin::LEVEL_2)
                    ->field('id,admin_note')
                    ->select();
        }elseif ($row['level'] == Selladmin::LEVEL_2) {
            $selladminlist=Selladmin::where('pid','=',$id)
                    ->field('id,admin_note')
                    ->select();
        }
        //查询地区
        $ProvCityArea = new ProvCityArea();
        $prov = $ProvCityArea->where('level=1')->field('id,name')->select();

        $store = new Store();
        $store_name = input('get.store_name');
        $phone = input('get.phone');
        $provdata = input('get.provdata');
        if ($store_name) {
            $where['store_name'] = ['like', "%$store_name%"];
            $query['store_name'] = $store_name;
        }
        if ($phone) {
            $where['keeper_phone'] = $phone;
            $query['keeper_phone'] = $phone;
        }
        if ($provdata) {
            $where['prov'] = $provdata;
            $query['provdata'] = $provdata;
        }
        $starttime = input('param.starttime');
        $endtime = input('param.endtime');
        if ($endtime && $starttime) {
            $time = strtotime($starttime);
            $time2 = strtotime($endtime) + 24 * 60 * 60;
            $where['add_time'] = array('between', array($time, $time2));
            $query['starttime'] = $starttime;
            $query['endtime'] = $endtime;
        } elseif (empty($endtime) && $starttime) {
            $time = strtotime($starttime);
            $time2 = $time + 24 * 60 * 60;
            $where['add_time'] = array('between', array($time, $time2));
            $query['starttime'] = $starttime;
        }
        $where['auditstore'] = 1;
        $query['auditstore'] = 1;
        $where['is_del'] = 1;
        $query['is_del'] = 1;
        $where['sell_id'] = 0;
        $query['sell_id'] = 0;
        $where['add_time'] = ['>',1546272000];
        $query['add_time'] = ['>',1546272000];
        $where['level'] = 1;
        $query['level'] = 1;
        $ctm_id = session('S_ID');
        $selladmin = Selladmin::where('id','=',$ctm_id)->field('id,level')->find();
        $level = $selladmin['level'];
        if($level==0 or $level==1){//超级管理员和总经理
            $where['assign'] = 0;
        }elseif ($level==2) {//经理
            $where['assign'] = $ctm_id;
        }
        $storeList = Store::with('ProvCityArea,Selladmin')
                ->where($where)
                ->field("id,store_name,store_keeper,store_address,keeper_phone,add_time,prov,msg,sell_id,level,expire_time")
                ->order("add_time desc")
                ->paginate(12)
                ->appends($query);
        return view('assignstore', [
            'storeList' => $storeList,
            'store_name' => $store_name,
            'phone' => $phone,
            'selladmin' => $selladminlist,
            'prov' => $prov,
            'provdata' => $provdata,
            'starttime' => $starttime,
            'endtime' => $endtime,
            'adminid' => 1,
        ]);
    }
    
    /*
     * 分配店铺
     * author xfwed 
     * date 2019.01.21
     */

    public function AssignStore2() {
        $store_ids = input('param.store_ids');
        $sell_id = input('param.sell_id');
        $s_id = session('S_ID');
        if(empty($store_ids)){
            return $this->ajaxReturn(1, "请选择店铺", null);
        }
        if(empty($sell_id)){
            return $this->ajaxReturn(1, "请选择分配人", null);
        }
        $sellrow = Selladmin::where('id','=',$s_id)->find();
        $level = $sellrow['level'];
        if($level == 1){//总经理
            $data['assign'] = $sell_id;
        }elseif ($level == 2) {//经理
            $data['sell_id'] = $sell_id;
        }elseif ($level == 0) {//超级管理员
            return $this->ajaxReturn(1, "这小事，交给经理吧", null);
        }elseif ($level == 3) {
            return $this->ajaxReturn(1, "快联系经理给你分配吧", null);
        }
        $savestore = Store::where('id','in',$store_ids)->update($data);
        if($savestore){
            return $this->ajaxReturn(0, "分配成功", null);
        }
    }
}
